/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.techshop.dao.impl;

import com.techshop.dao.CommentDao;
import com.techshop.model.Comment;
import java.util.List;
import org.hibernate.Query;
import org.springframework.dao.DataAccessResourceFailureException;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

/**
 *
 * @author hai
 */
public class CommentDaoImpl extends HibernateDaoSupport implements CommentDao{

    @Override
    public Comment getById(int commentId) {
        try
        {
            return (Comment)getSession().get(Comment.class, commentId);
        }
        catch (DataAccessResourceFailureException e)
        {
            System.err.printf("Error: ", e.toString());
            return null;
        }
    }

    @Override
    public List<Comment> findAll() {
        try
        {
            System.out.println("CCCCCCCCCCCCCCCCCCCCCCCC---CCCCCCCCCCCCCCCC");
            Query q = getSession().createQuery("from Comment");
            q.setFirstResult(0);
            q.setMaxResults(100);
            return q.list();
           // return getSession().createQuery("from Comment").list();
        }
        catch (DataAccessResourceFailureException e)
        {
            System.err.printf("Error: ", e.toString());
            return null;
        }
    }

    @Override
    public boolean insert(Comment comment) {
          try
        {
            getHibernateTemplate().save(comment);
            return true;
        }
        catch (DataAccessResourceFailureException e)
        {
            System.err.printf("Error: ", e.toString());
            return false;
        }
    }

    @Override
    public boolean update(Comment comment) {
        try
        {
            if (getById(comment.getId()) == null)
            {
                return false;
            }
            else
            {
                getHibernateTemplate().update(getHibernateTemplate().merge(comment));
                return true;
            }
        }
        catch (DataAccessResourceFailureException e)
        {
            System.err.printf("Error: ", e.toString());
            return false;
        }
    }

    @Override
    public boolean delete(Comment comment) {
        try
        {
            if (getById(comment.getId()) == null)
            {
                return false;
            }
            else
            {
                getHibernateTemplate().delete(getHibernateTemplate().merge(comment));
                return true;
            }
        }
        catch (DataAccessResourceFailureException e)
        {
            System.err.printf("Error: ", e.toString());
            return false;
        }
    }
    
}
